import { useEffect, useState } from 'react'
import { PictureOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons'
import { Upload, message, Image, Button, Tooltip } from 'antd'

const getBase64 = (file: any) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })

const UploadComponent = (props: any) => {
  const [previewImage, setPreviewImage] = useState('')
  const [previewOpen, setPreviewOpen] = useState(false)
  const [fileList, setFileList] = useState([])

  useEffect(() => {
    if (props.value && typeof props.value === 'string') {
      setFileList(props.value.split(',')?.map((item: string) => ({ url: item })))
    }
  }, [props.value])

  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    setPreviewImage(file.url || file.preview)
    setPreviewOpen(true)
  }

  const handleChange = (info: any) => {
    const { fileList: newFileList } = info
    setFileList(newFileList)
    if (info?.file?.response?.code === 402) {
      message.error(info?.file?.response?.message)
      setTimeout(() => {
        setFileList(newFileList.slice(0, newFileList.length - 1))
      }, 500)
    } else {
      if (info.file.status === 'done') {
        setFileList(newFileList)
        const url = newFileList?.map((item: any) => item?.response?.data?.linkUrl || item?.url).join(',')
        props.onChange(url)
      }
    }
  }

  const handleOnRemove = (file: any) => {
    const newFileList = fileList?.filter((item: any) => item.uid !== file.uid)
    setFileList(newFileList)
    const url = newFileList?.map((item: any) => item?.response?.data?.linkUrl || item?.url).join(',')
    props.onChange(url)
  }

  const uploadButton = (
    <Tooltip title={props.title ? props.title : '图片替换'}>
      <PictureOutlined />
    </Tooltip>
  )
  return (
    <>
      <Upload
        action={`/api/sop/sop/file/upload`}
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        onRemove={handleOnRemove}
        disabled={!!props.disabled}
        accept={props.accept ? props.accept : 'image/*'}
        maxCount={props.max ? props.max : 1}
        showUploadList={false}
      >
        {props.disabled ? null : fileList.length > props.max ? null : uploadButton}
      </Upload>
    </>
  )
}

export default UploadComponent
